﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
using System.Reflection;

using Microsoft.Xna.Framework;

using GamePlugins;

namespace WindowsGame
{

    static class PluginLoader
    {

        public static void LoadPlugins(String path, Microsoft.Xna.Framework.Game game, GameComponentCollection components)
        {

            System.Console.Out.WriteLine("Loading plugins...");
            System.Console.Out.WriteLine("Loading path \"" + path + "\"");

            System.IO.DirectoryInfo DirInfo = new System.IO.DirectoryInfo(path);
            if (!DirInfo.Exists)
            {
                System.Console.Out.WriteLine("Can't find plugins derectory (" + path + ")");
                return;
            }

            System.IO.DirectoryInfo[] pluginDirsInfo = DirInfo.GetDirectories();

            foreach (DirectoryInfo pluginDirInfo in pluginDirsInfo)
            {

                System.IO.FileInfo[] FileInfo;
                FileInfo = pluginDirInfo.GetFiles("*.dll");

                for (int i = 0; i < FileInfo.Length; i++)
                {
                    System.Console.Out.WriteLine("Loading plugin \"" + FileInfo[i].Name + "\"");

                    Assembly assembly;
                    assembly = Assembly.LoadFrom(FileInfo[i].FullName);

                    Type[] types = assembly.GetTypes();

                    for (int j = 0; j < types.Length; j++)
                    {

                        GamePlugin plugin = null;

                        if (types[j].BaseType.FullName.Equals("GamePlugins.GamePlugin"))
                        {
                            plugin = (GamePlugin)Activator.CreateInstance(types[j]);
                            plugin.setContentPath(path + "\\" + pluginDirInfo.Name + "\\" + "Content");
                            components.Add(plugin.getGameComponent(game));
                        }

                    }

                    System.Console.Out.WriteLine("Plugin loaded");
                }
            }

            System.Console.Out.WriteLine("Plugins loaded");

        }

    }

}
